<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="分类名称">
        <el-input v-model="bindForm.name" placeholder="分类名称" />
      </el-form-item>
      <el-form-item label="分类状态">
        <!-- clearable	是否可以清空选项 -->
        <el-select v-model="bindForm.status" placeholder="分类状态" clearable>
          <el-option label="开启" :value="1" />
          <el-option label="关闭" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="openDialog">新建</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="tableData"
      style="width: 100%"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        prop="name"
        label="分类名称"
      />
      <!-- 用插槽方式把分类状态翻译成中文 -->
      <el-table-column
        prop="status"
        label="分类状态"
      >
        <template slot-scope="{row}">
          <span v-if="row.status===1">开启</span>
          <span v-if="row.status===0">关闭</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="cover"
        label="分类图片"
      >
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.cover"
            :preview-src-list="[row.cover]"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="primary"
            @click="changeStatus(scope)"
          >开启</el-button>
          <el-button
            v-else
            size="mini"
            @click="changeStatus(scope)"
          >关闭</el-button>
          <el-button
            size="mini"
            @click="findCategoryFun(scope)"
          >修改</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template>
      <div class="block">
        <el-pagination
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="分类图片" prop="cover">
          <upload-img v-model="form.cover" @getUrl="getCover" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumibt('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { categoryCreate, getCategoryList, categoryDelete, findCategory, updateCategory, editStatus } from '@/api/goods/goodsCategory.js'
import uploadImg from '@/components/Common/uploadImg.vue'
export default {
  components: { uploadImg },
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      form: {
        name: '', // 分类名称
        cover: '' // 分类图片
      },
      pageNo: 1, // 第几页
      pageSize: 5, // 每页显示的条数
      total: 0, // 总共几条数据
      categoryId: '', // 根据是否有categoryId判断是弹窗新建还是修改
      title: '新建商品分类',
      listLoading: true, // 表格的loading状态，初始值是true表示打开的时候。表格是在loading
      searchForm: {
        name: null,
        status: null
      },
      bindForm: {
        name: null,
        status: null
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '请选择图片', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getListFun()
  },
  methods: {
    onSearch() {
      this.searchForm.name = this.bindForm.name
      this.searchForm.status = this.bindForm.status
      this.getListFun()
    },
    getListFun() {
      getCategoryList({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        name: this.searchForm.name,
        status: this.searchForm.status
      }).then(res => {
        console.log(res)
        this.listLoading = false// 列表请求结束，则把表格的loading关闭
        const { code, data } = res
        if (code === 200) {
          this.total = data.pagination.count
          this.tableData = data.list
        }
      })
    },
    // 修改状态
    changeStatus({ row }) {
      const { status, _id } = row
      // 这里修改状态是关闭跟开启公用一个接口
      // 所以要判断目前的单项状态是开启还是关闭，如果是开启的1,则需要传递status = 0,反之则传status = 1
      let _status = 0 // 定义要传递的分类状态
      let message = '关闭成功'
      if (status === 0) {
        _status = 1// 如果当前是关闭状态，则要传递状态1把分类修改为开启
        message = '开启成功'
      } else {
        _status = 0// 如果当前是开启状态，则要传递状态1把分类修改为关闭
        message = '关闭成功'
      }
      editStatus(_id, { status: _status }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message({
            type: 'success',
            message
          })
          this.getListFun()// 请求成功则刷新列表
        }
      })
    },
    getCover(url) {
      this.form.cover = url
      console.log(url)
    },
    openDialog() {
      this.title = '新建商品分类'
      // 点击新增按钮，把form和categoryId都初始化
      this.categoryId = ''
      this.form = {
        name: '', // 分类名称
        cover: '' // 分类图片
      }
      console.log('图片', this.form.cover)
      // 点击新增按钮，打开弹窗
      this.dialogFormVisible = true
    },
    // 新建分类
    categoryCreateFun() {
      categoryCreate(this.form).then(res => {
        const { code } = res
        if (code === 200) {
          // 请求成功则刷新列表并关闭弹窗
          this.dialogFormVisible = false
          this.getListFun()
          this.$message({
            type: 'success',
            message: '新建成功!'

          })
        }
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '新建失败!'

        })
      })
    },
    // 删除分类
    handleDelete({ row }) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确认按钮走这里的逻辑
        categoryDelete(row._id).then(res => {
          const { code } = res
          if (code === 200) {
            this.getListFun()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        }).catch(() => {
        // 点击取消按钮走这里的逻辑
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      })
    },
    // 修改
    updateCategoryFun() {
      updateCategory(this.categoryId, this.form).then(res => {
        const { code } = res
        if (code === 200) {
          // 请求成功则刷新列表并关闭弹窗
          this.dialogFormVisible = false
          this.getListFun()
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '修改失败!'

        })
      })
    },
    // 查询被修改的商品
    findCategoryFun({ row }) {
      this.openDialog()
      this.title = '修改商品分类'
      findCategory(row._id).then(res => {
        const { code, data } = res
        if (code === 200) {
          // 请求成功则赋值到data里面的form把值回显
          const { name, cover, _id } = data
          this.categoryId = _id // 把分类id赋值到data上定义的categoryId，为了在弹窗确认的时候判断是修改还是新增
          this.form = {
            name,
            cover
          }
        }
      })
    },
    // 点击确认按钮触发
    sumibt(formName) {
      // 判断是否有id，如果有则是修改，没有则是新增

      if (this.categoryId) {
        this.updateCategoryFun()
      } else {
        this.categoryCreateFun()
      }
      this.$refs[formName].validate((valid) => {
        // if (valid) {
        //   alert('submit!')
        // } else {
        //   console.log('error submit!!')
        //   return false
        // }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getListFun()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.pageNo = val
      this.getListFun()
      console.log(`当前页: ${val}`)
    }
  }
}
</script>

<style scoped lang="scss">
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avadtar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .demo-form-inline{
  margin-top: 20px;
}
</style>
